package com.iflytek.exam.service.impl;

import com.iflytek.common.core.domain.entity.SysUser;
import com.iflytek.exam.domain.*;
import com.iflytek.exam.mapper.ChoiceMapper;
import com.iflytek.exam.mapper.QuestionExamMapper;
import com.iflytek.exam.service.*;
import com.iflytek.exam.utils.StringSplitter;
import com.iflytek.exam.vo.AnswersVo;
import com.iflytek.system.service.ISysUserService;
import com.iflytek.xfapi.chat.xfChat4.ChatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class AnswerSubmitServiceImpl implements AnswerSubmitService {
    @Autowired
    ChoiceMapper choiceService;

    @Autowired
    IJudgeService judgeService;

    @Autowired
    IShortAnswerService shortAnswerService;

    @Autowired
    QuestionExamService questionExamService;

    @Autowired
    QuestionExamMapper questionExamMapper;
    @Autowired
    IPaperInfoService paperInfoService;

    @Autowired
    ICreateExamService examService;

    @Autowired
    IExamGradeService examGradeService;

    @Autowired
    ISysUserService userService;

    @Autowired
    IExamSetService examSetService;

    @Override
    public int insertPaper(AnswersVo answersVo, Long examId) {
        //保存试卷成绩信息
        ExamGrade examGrade = new ExamGrade();
        //初始化试卷信息
        examGrade.setSingleTotalScore(0L);
        examGrade.setMultipleTotalScore(0L);
        examGrade.setJudgeTotalScore(0L);
        examGrade.setShortAnswerTotalScore(0L);
        examGrade.setTime(answersVo.getTime());
        //查询试卷
        CreateExam examById = examService.selectcreateExamById(examId);
        Long passLine = examById.getPassLine();
        //查询当前用户信息
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        SysUser sysUser = userService.selectUserByUserName(username);
        Long userId = sysUser.getUserId();
        //如果之前已经提交过，先删除提交记录,再重新添加，否则会重复添加
        List<PaperInfo> paperInfoByExamIdAndUserId = paperInfoService.selectPaperInfoByExamIdAndUserId(examId, userId);
        if (paperInfoByExamIdAndUserId.size() > 0) {
            //examGradeService.deleteExamGradeById()
            paperInfoService.deletePaperInfoByExamIdAndUserId(examId, userId);
        }
        if (answersVo.getSingleVo() != null) {
            answersVo.getSingleVo().forEach(singleAnswerVo -> {
                PaperInfo paperInfo = new PaperInfo();
                paperInfo.setUserId(userId);
                paperInfo.setExamId(examId);
                paperInfo.setQuId(singleAnswerVo.getId());
                paperInfo.setType(1); //单选题
                paperInfo.setContent(singleAnswerVo.getSelectedOption());
                Choice choiceById = choiceService.selectChoiceById(singleAnswerVo.getId());
                paperInfo.setQuBankId(choiceById.getQuBankId());
                //保存当前试题答案到数据库
                paperInfoService.insertPaperInfo(paperInfo);
                if (choiceById.getAnswer().equals(singleAnswerVo.getSelectedOption())) {
                    //更新当前考试单选题成绩
                    examGrade.setSingleTotalScore(examGrade.getSingleTotalScore() + examById.getSingleScore());
                }
            });
        }
        if (answersVo.getMultipleVo() != null) {
            answersVo.getMultipleVo().forEach(multipleAnswerVo -> {
                PaperInfo paperInfo = new PaperInfo();
                paperInfo.setQuId(multipleAnswerVo.getId());
                paperInfo.setType(2); //多选题
                paperInfo.setUserId(userId);
                paperInfo.setContent(StringSplitter.extractAndJoinChars(multipleAnswerVo.getSelectedOption()));
                paperInfo.setExamId(examId);
                Choice choiceById = choiceService.selectChoiceById(multipleAnswerVo.getId());
                paperInfo.setQuBankId(choiceById.getQuBankId());
                paperInfoService.insertPaperInfo(paperInfo);
                if (StringSplitter.extractAndSortChars(choiceById.getAnswer()).equals(StringSplitter.extractAndSortChars(StringSplitter.extractAndJoinChars(multipleAnswerVo.getSelectedOption())))) {
                    //更新当前考试多选题成绩
                    examGrade.setMultipleTotalScore(examGrade.getMultipleTotalScore() + examById.getMultipleScore());
                }
            });
        }
        if (answersVo.getJudgeVo() != null) {
            answersVo.getJudgeVo().forEach(judgeAnswerVo -> {
                PaperInfo paperInfo = new PaperInfo();
                paperInfo.setQuId(judgeAnswerVo.getId());
                paperInfo.setType(3); //判断题
                paperInfo.setUserId(userId);
                paperInfo.setUserId(userId);
                paperInfo.setContent(null == judgeAnswerVo.getSelectedOption() ? "" : String.valueOf(judgeAnswerVo.getSelectedOption()));
                paperInfo.setExamId(examId);
                Judge judgeById = judgeService.selectJudgeById(judgeAnswerVo.getId());
                paperInfo.setQuBankId(judgeById.getQuBankId());
                paperInfoService.insertPaperInfo(paperInfo);
                if (judgeById.getAnswer() == judgeAnswerVo.getSelectedOption()) {
                    //更新当前考试多选题成绩
                    examGrade.setSingleTotalScore(examGrade.getJudgeTotalScore() + examById.getJudgeScore());
                }
            });
        }
        if (answersVo.getShortAnswerVo() != null) {
            ExamSet examSet = examSetService.selectExamSetByExamId(examId);
            //调用接口自动批阅简答题
            if (examSet.getForcedWinding() == 1) {
                //修改为已批阅
                examGrade.setStatus(1);
                answersVo.getShortAnswerVo().forEach(shortAnswerVo -> {
                    PaperInfo paperInfo = new PaperInfo();
                    paperInfo.setQuId(shortAnswerVo.getId());
                    paperInfo.setType(4); //简答题
                    paperInfo.setUserId(userId);
                    paperInfo.setContent(shortAnswerVo.getUserAnswer());
                    paperInfo.setExamId(examId);
                    ShortAnswer shortAnswerById = shortAnswerService.selectShortAnswerById(shortAnswerVo.getId());
                    paperInfo.setQuBankId(shortAnswerById.getQuBankId());
                    paperInfoService.insertPaperInfo(paperInfo);
                    // 调用自动批改试卷接口返回分数
                    int percent = 60;
                    try {
                        percent = ChatUtil.xfChatUltra4(shortAnswerById.getTitle(), shortAnswerById.getAnswer(), shortAnswerVo.getUserAnswer());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    examGrade.setShortAnswerTotalScore(examGrade.getShortAnswerTotalScore() + (examById.getShortAnswerScore() * percent) / 100);
                });
            } else {
                examGrade.setStatus(0);
            }
        }

        examGrade.setExamId(examId);
        examGrade.setUserId(userId);
        examGrade.setTotalScore(0L);
        examGrade.setTime(answersVo.getTime());
        examGrade.setTime(answersVo.getTime());
        examGrade.setStatus(1);//如果没有简答题系统自动批阅选择、判断题
        examGrade.setTotalScore(examGrade.getSingleTotalScore() + examGrade.getMultipleTotalScore() + examGrade.getJudgeTotalScore() + examGrade.getShortAnswerTotalScore());
        if (examGrade.getTotalScore() >= passLine) {
            examGrade.setIsPass(1); //成绩合格
        } else {
            examGrade.setIsPass(0);
        }
        //先删除原来的成绩再重新保存一份
        examGradeService.deleteExamGradeByExamIdAndUserId(examId, userId);
        //保存成绩
        return examGradeService.insertExamGrade(examGrade);
    }
}
